import { Inject, Injectable } from '@nestjs/common';
import { DbService } from 'src/db/db.service';
import { AddBookDto } from './dto/add-book.dto';
import { Book } from './entities/book.entity';
import { UpdateBookDto } from './dto/update-book.dto';

@Injectable()
export class BookService {
  @Inject(DbService)
  dbService: DbService;

  async add(addBookDto: AddBookDto) {
    const books = await this.dbService.read();
    const date = new Date();
    const book = {
      ...addBookDto,
      id: date.getTime() + '',
      updateTime: new Date(),
      createTime: new Date(),
    };
    books.push(book);
    await this.dbService.write(books);
    return {
      code: 0,
      message: '添加成功',
      data: book,
    };
  }

  async delete(id: string) {
    const books: Book[] = await this.dbService.read();
    const index = books.findIndex((book) => book.id === id);
    if (index === -1) {
      return {
        code: 1,
        message: '书籍不存在',
        data: null,
      };
    }
    books.splice(index, 1);
    await this.dbService.write(books);
    return {
      code: 0,
      message: '删除成功',
      data: null,
    };
  }

  async update(updateBookDto: UpdateBookDto) {
    const books: Book[] = await this.dbService.read();
    const index = books.findIndex((book) => book.id === updateBookDto.id);
    if (index === -1) {
      return {
        code: 1,
        message: '书籍不存在',
      };
    }
    books[index] = {
      ...books[index],
      ...updateBookDto,
      updateTime: new Date(),
    };

    await this.dbService.write(books);
    return {
      code: 0,
      message: '更新成功',
      data: books[index],
    };
  }

  async detail(id: string) {
    const books: Book[] = await this.dbService.read();
    console.log(typeof books, id);
    const book = books.find((item) => item.id === id);
    console.log(book);
    if (!book) {
      return {
        code: 1,
        message: '书籍不存在',
        data: null,
      };
    }
    return {
      code: 0,
      message: '查询成功',
      data: book,
    };
  }

  async list(name?: string) {
    const books: Book[] = await this.dbService.read();
    return {
      code: 0,
      message: '查询成功',
      data: name ? books.filter((item) => item.title.includes(name)) : books,
    };
  }
}
